package com.xunk.equipment.interceptor;

import com.xunk.common.core.text.Convert;
import com.xunk.common.core.utils.StringUtils;
import com.xunk.common.security.utils.SecurityUtils;
import com.xunk.equipment.context.RequestHeaderContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ProjectName: xunk
 * @Package: com.xunk.equipment.interceptor
 * @ClassName: ControllerInterceptor
 * @Author: luanzhiwei
 * @Description: 拦截器统一处理请求头
 * @Date: 2021/4/7 15:37
 * @Version: 1.0
 */
@Component
@Slf4j
public class ControllerInterceptor extends HandlerInterceptorAdapter {

    private static final String Authorization_PARAM = "Authorization";


    public ControllerInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        initHeaderContext(request);
        super.preHandle(request, response, handler);
        return true;
    }

    private void initHeaderContext(HttpServletRequest request) {
        String bearerToken = request.getHeader(Authorization_PARAM);
        String token = StringUtils.EMPTY;
        if (StringUtils.isNotBlank(bearerToken)) {
            token = bearerToken.split(" ")[1];
        }
        new RequestHeaderContext.RequestHeaderContextBuild()
                .token(token)
                //赋值userid，用于智家查询绑定refreshToken，否则需要重复登录
                .userId(Convert.toStr(SecurityUtils.getUserId()))
                .bulid();
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        RequestHeaderContext.clean();
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHeaderContext.clean();
        super.afterCompletion(request, response, handler, ex);
    }


}
